package tobsn.locationcalendar.map.overlays;

import java.util.ArrayList;
import java.util.List;

import tobsn.locationcalendar.db.DBAdapter;
import tobsn.locationcalendar.db.DBOpenHelper;
import tobsn.locationcalendar.map.TobsnMapActivity;
import android.database.Cursor;
import android.graphics.drawable.Drawable;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;

public class ExistingPONOverlay extends
		ItemizedOverlay<NotificationOverlayItem> {

	private static final String TAG = "ExistingNotificationOverlay";
	private List<NotificationOverlayItem> mOverlayItems = new ArrayList<NotificationOverlayItem>();
	private TobsnMapActivity mContext;
	private DBAdapter mDBAdapter;
	private String mSelectedItemText;

	public ExistingPONOverlay(Drawable defaultMarker) {
		super(defaultMarker);
		populate();
	}

	public ExistingPONOverlay(Drawable defaultMarker,
			TobsnMapActivity context) {
		super(boundCenter(defaultMarker));
		mContext = context;
		mDBAdapter = new DBAdapter(context);
		populate();
	}

	/**
	 * Is fired when the user presses on an already existing mark.
	 */
	@Override
	protected boolean onTap(int index) {
		NotificationOverlayItem item = mOverlayItems.get(index);
		mContext.showPONPopup(item.getId());
		return true;
	}

	public void updateOverlay() {
		mOverlayItems.clear();
		// you have to call this if you edit the list with items, otherwise an
		// arrayindexoutofbounds exception could occur
		setLastFocusedIndex(-1);
		mDBAdapter.open();
		Cursor c = mDBAdapter.fetchAllPON();
		while (c.moveToNext()) {
			int latitude = c.getInt(DBOpenHelper.LATITUDE_INT);
			int longitude = c.getInt(DBOpenHelper.LONGITUDE_INT);
			String text = c.getString(DBOpenHelper.TEXT_INT);
			int id = c.getInt(DBOpenHelper.ROW_ID_INT);
			GeoPoint p = new GeoPoint(latitude, longitude);
			NotificationOverlayItem item = new NotificationOverlayItem(p, text,
					null, id);
			mOverlayItems.add(item);
		}
		c.close();
		mDBAdapter.close();
		populate();
	}

	@Override
	protected NotificationOverlayItem createItem(int i) {
		return mOverlayItems.get(i);
	}

	@Override
	public int size() {
		return mOverlayItems.size();
	}

	public String getSelectedItemText() {
		return mSelectedItemText;
	}
}
